package cn.crystalling.app.attendance;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RadioButton;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;

@SuppressWarnings("all")
public class ListViewAdapter extends BaseAdapter {
    private ArrayList<Student> mList;
    private LayoutInflater mInflater;
    //解决Listview的重复RadioButton 的 view问题
    private HashMap<Integer,View> viewMap;

    ListViewAdapter(Context context, ArrayList<Student> list) {
        mList = list;
        mInflater = LayoutInflater.from(context);
        viewMap = new HashMap<Integer,View>();
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int i) {
        return mList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        //view 只在第一页显示的那些item是被创建的，当你滚动到下一页的时候，就会重复使用，这时候就会出问题
        //自己创建mapView,存入Map,避免重复使用
        View mapView;
        ViewHolder viewHolder;
        if (viewMap.get(i) == null) {
            viewHolder = new ViewHolder();
            mapView = mInflater.inflate(R.layout.view_item, null);
            viewHolder.numTxt = (TextView) mapView.findViewById(R.id.numTxt);
            viewHolder.nameTxt = (TextView) mapView.findViewById(R.id.nameTxt);
            viewHolder.trueBtn = (RadioButton) mapView.findViewById(R.id.trueBtn);
            viewHolder.falseBtn = (RadioButton) mapView.findViewById(R.id.falseBtn);
            viewHolder.otherReasonBtn = (RadioButton) mapView.findViewById(R.id.otherReasonBtn);

            viewMap.put(i,mapView);
            mapView.setTag(viewHolder);
        } else {
            mapView = viewMap.get(i);
            viewHolder = (ViewHolder) mapView.getTag();
        }
        Student tempStu = mList.get(i);
        viewHolder.numTxt.setText(String.valueOf(tempStu.getNum()));
        viewHolder.nameTxt.setText(tempStu.getName());

        //读取每个学生的状态并显示
        int state = tempStu.getState();
        if(state == 1){
            viewHolder.trueBtn.setChecked(true);
        }else if(state == 2){
            viewHolder.falseBtn.setChecked(true);
        }else if(state == 3){
            viewHolder.otherReasonBtn.setChecked(true);
        }

        return mapView;
    }

    public HashMap<Integer,View> getViewMap(){
        return viewMap;
    }

    private class ViewHolder {
        TextView numTxt;
        TextView nameTxt;
        RadioButton trueBtn;
        RadioButton falseBtn;
        RadioButton otherReasonBtn;
    }
}


